<template>
  <div>
    <el-radio-group v-model="listQuery.isMy" @change="handleSearchList">
      <el-radio-button label="1">我的</el-radio-button>
      <el-radio-button label="0">全部</el-radio-button>
    </el-radio-group>
    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='applyListXGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>
        <template #form>
          <div>
            <!--搜索-->
            <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
              <el-form-item label="申请人：">
                <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
                  <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
                <el-form-item label="客户名称：">
                  <el-select
                    clearable
                    v-model="listQuery.customerId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :remote-method="querySearch">
                    <el-option
                      v-for="item in querySearchList"
                      :key="item.customerId"
                      :label="item.customerName"
                      :value="item.customerId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="产品线：">
                  <el-select v-model="listQuery.goodsLineId" filterable clearable>
                    <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="申请时间：">
                  <el-date-picker
                    v-model="listQuery.date"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button
                      @click="handleSearchList()"
                      type="primary">
                      查询
                    </el-button>
                </el-form-item>
            </el-form>
          </div>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <el-link @click="toDetail(row)" type="primary"  style="font-size:12px;vertical-align: middle">{{row.customerName}}</el-link>
        </template>
        <template #toolbar_buttons>
          <el-radio-group v-model="listQuery.applyState" @change="handleSearchList" size="mini">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="0">待审核</el-radio-button>
            <el-radio-button label="1">审核通过</el-radio-button>
          </el-radio-group>
        </template>
        <template #for_default2="{row,rowIndex}">
          <el-button type="text" size="small" @click="cancelItem(row)" v-if="row.applyState == 0 && listQuery.isMy == 1 ">取消</el-button>
          <el-button type="text" size="small" @click="showPop(row)" v-if="row.applyState == 0 && listQuery.isMy == 0 ">审核</el-button>
        </template>
      </vxe-grid>
    </div>
    <el-dialog :close-on-click-modal="false" title="审核" :visible.sync="dialogVisible" width="400px">
      <el-form  :model="form" size="mini" label-width="100px" ref="form" :rules="rules">
           <el-form-item label="申请人：">{{curItem.userName}}</el-form-item>
           <el-form-item label="公司名称：">{{curItem.customerName}}</el-form-item>
           <el-form-item label="产品线：">{{curItem.goodsLineName}}</el-form-item>
           <el-form-item label="备注：" prop="remark">
                <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.remark"></el-input>
           </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="handleConfirm('2')" :loading="btnLoading2">审核不通过</el-button>
          <el-button type="primary" @click="handleConfirm('1')" :loading="btnLoading">审核通过</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getOrderUsersList,getCustomerOption,getCustomerSetting} from '@/api/partner'
import {customerNewApplyList,customerNewAduApplyState} from '@/api/company'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  date:[],
  "customerId" : "", //公司名称
  "goodsLineId" : "", //产品线名称
  "userId" :'' , //用户名称
  "applyState" :'' , //审核状态  0待审核 1审核成功 2审核失败 3取消',
  "isMy" : '1', //1 我的申请 0 全部 ,
  "cglId" :'' , //产品线id,
  "pageNum" : 1,      //第几页，默认1
  "pageSize" : 10     //每页几条，默认10条
};

const defaultListQuery1={
  "pageNum" : 1,      //第几页，默认1
  "pageSize" : 10     //每页几条，默认10条
};

const defaultform={
  "remark" : '',

};
export default {
  name: "index",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      userOptionList:[],

      gridOptions:{
        loading:this.listLoading,
        border: true,
        id: 'applyList',
        align:'center',
        autoResize:true,
        size:'mini',
        rowConfig: {
          keyField: 'applyId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        checkboxConfig:{
          reserve:true
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [
          {
            field: 'userName',
            title: '申请人',
            width: 100,
          },
          {
            field: 'customerName',
            title: '客户名称',
            width: 150,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'goodsLineName',
            title: '产品线',
            width: 100,
          },
          {
            field: 'createdAt',
            title: '申请时间',
            width: 150,
          },
          {
            field: 'applyRemark',
            title: '申请原因',
            showOverflow:true,
            width: 150,

          },
          {
            field: 'targetNum',
            title: '申请目标',
            width: 100,
          },
          {
            field: 'applyState',
            title: '状态',
            width: 100,
            formatter ({ cellValue }) {
              if(cellValue == 0){
                return '待审核'
              }else if(cellValue == 1){
                return '审核成功'
              }else if(cellValue == 2){
                return '审核失败'
              }else if(cellValue == 3){
                return '取消'
              }
            }
          },
          {
            field: 'checkTime',
            title: '审核时间',
            width: 150,
          },
          {
            field: 'checkRemark',
            title: '审核备注',
            width: 150,
            showOverflow:true,
          },
          {
            field: 'holdTime',
            title: '持有天数',
            width: 100,
          },
          {
            field: 'actualNum',
            title: '实际成交量',
            width: 100,
          },
          {
            field: 'proportion',
            title: '成交率',
            width: 100,
          },
          {
            field: '',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              default: 'for_default2',
            },
          },
        ],
        data:[],
      },

      querySearchList:[],
      radio1:'',

      dialogVisible:false,
      form:JSON.parse(JSON.stringify(defaultform)),
      btnLoading:false,
      btnLoading2:false,
      rules:{
        remark: [{required: true, message: '此项必填', trigger: 'blur'},],
      },
      curItem:{},
      goodsLineList:[]


    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    departmentPL(){
      if(this.roles.indexOf("departmentPL") != -1){
        return true
      }else{
        return false
      }
    },
  },
  components : {
  },
  created() {
      this.getUserOptionList();
      this.getCustomerSettingList()
  },
  filters: {

  },
  methods:{
    //获取客户配置
    getCustomerSettingList(){
      getCustomerSetting().then((res)=>{
        res.forEach((el)=>{
          if(el.cdtCode == 'goods_line'){
            this.goodsLineList = el.data
          }
        });
      })
    },
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerGoodsLineInfo',query:{id:item.customerId}});
      window.open(routeData.href);
    },
    cancelItem(item){
      this.$confirm('是否确认取消?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let pa = {};
        pa.applyId = item.applyId;
        pa.applyState = 3;
        customerNewAduApplyState(pa).then(()=>{
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.getList()
        })
      }).catch(() => {

      });
    },
    //显示审核
    showPop(item){
       this.dialogVisible = true;
       this.curItem = JSON.parse(JSON.stringify(item));
       this.form = JSON.parse(JSON.stringify(defaultform));
    },
    handleConfirm(type){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = type == 1;
          this.btnLoading2 = type == 2;
          let pa = JSON.parse(JSON.stringify(this.form));
          pa.applyId = this.curItem.applyId;
          pa.applyState = type
          customerNewAduApplyState(pa).then(()=>{
            this.btnLoading = false
            this.btnLoading2 = false
            this.dialogVisible = false;
            this.getList()
          }).catch(()=>{
            this.btnLoading = false
            this.btnLoading2 = false
          })
        }
      })
    },
    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= '') {
        getCustomerOption({keywords: queryString}).then((res) => {
          this.querySearchList = res;
        })
      }
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },

    //选择员工名称
    handleSelectUserName(key,item){
      this.listQuery[key] = item.userId;
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //获取列表
    getList() {
      this.listLoading = true;
      customerNewApplyList(this.listQuery).then(response => {
        this.gridOptions.data = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },

  },
}
</script>

<style  lang="scss">

</style>
